package com.example.jumpotherapp

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener {
            launchPage("com.example.launchmodedemo", "com.example.launchmodedemo.BActivity")
        }
    }

    private fun launchPage(appPackageName: String, activityPath: String) {
        val intent = Intent()
        val comp = ComponentName(appPackageName, activityPath)
        intent.component = comp
        intent.putExtra("other", "true")
        intent.action = "android.intent.action.VIEW"
        startActivity(intent)
    }

    /**
     * 跳转到指定app，如跳转到qq
     * launchApp(this, "com.tencent.mobileqq")
     */
    private fun launchApp(context: Context, appPackageName: String) {
        //判断当前手机是否有要跳入的app
        if (isAppInstalled(context, appPackageName)) {
            //如果有根据包名跳转
            context.startActivity(context.packageManager.getLaunchIntentForPackage(appPackageName))
        } else {
            //如果没有，走进入系统商店找到这款APP，提示你去下载这款APP的程序
            goToMarket(context, appPackageName)
        }
    }

    //这里是进入应用商店，下载指定APP的方法。
    private fun goToMarket(context: Context, packageName: String) {
        val uri: Uri = Uri.parse("market://details?id=$packageName")
        val goToMarket = Intent(Intent.ACTION_VIEW, uri)
        try {
            context.startActivity(goToMarket)
        } catch (e: Exception) {
        }
    }

    //这里是判断APP中是否有相应APP的方法
    private fun isAppInstalled(context: Context, packageName: String): Boolean {
        return try {
            context.packageManager.getPackageInfo(packageName, 0)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
}